/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui;

import static gui.GUIUtils.getTextFromPasswordField;

import java.awt.HeadlessException;
import java.io.IOException;
import java.util.List;

import javax.imageio.ImageIO;
import javax.swing.JOptionPane;

import algorithms.SHA1;
import core.exceptions.DBAccessException;
import core.objects.BaseObject;
import core.objects.User;
import db.DBAccessEngine;

/**
 *
 * @author abadi
 */
public class AuthenticationForm extends javax.swing.JFrame {

    private static final long serialVersionUID = 1L;

    /**
     * Creates new form AuthenticationForm
     */
    public AuthenticationForm() {
        initComponents();
        setLocationRelativeTo(null);
    }

    /**
     * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this
     * code. The content of this method is always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanelFullWindow = new javax.swing.JPanel();
        jLabelWelcome = new javax.swing.JLabel();
        jLabelUserName = new javax.swing.JLabel();
        jLabelPassword = new javax.swing.JLabel();
        jTextFieldUserName = new javax.swing.JTextField();
        jPasswordField = new javax.swing.JPasswordField();
        jButtonLogin = new javax.swing.JButton();
        jLabelSignUp = new javax.swing.JLabel();
        jLabelConstructDB = new javax.swing.JLabel();
        
        try {
        	setIconImage(ImageIO.read(JFrameConstructDB.class.getResourceAsStream("/resources/icon.png")));
		} catch (IOException exception) {
			//do nothing, let java default icon take over
		}

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Loan-a-Book");
        setBackground(new java.awt.Color(255, 255, 255));
        setResizable(false);

        jPanelFullWindow.setBackground(new java.awt.Color(51, 153, 255));

        jLabelWelcome.setFont(new java.awt.Font("Trebuchet MS", 1, 24)); // NOI18N
        jLabelWelcome.setForeground(new java.awt.Color(153, 255, 153));
        jLabelWelcome.setText("Welcome To Loan-a-Book!");

        jLabelUserName.setFont(new java.awt.Font("Trebuchet MS", 1, 13)); // NOI18N
        jLabelUserName.setForeground(new java.awt.Color(153, 255, 153));
        jLabelUserName.setText("User name");

        jLabelPassword.setFont(new java.awt.Font("Trebuchet MS", 1, 13)); // NOI18N
        jLabelPassword.setForeground(new java.awt.Color(153, 255, 153));
        jLabelPassword.setText("Password");

        jTextFieldUserName.addActionListener(new java.awt.event.ActionListener() {
            @Override
			public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldUserNameActionPerformed(evt);
            }
        });

        jPasswordField.addActionListener(new java.awt.event.ActionListener() {
            @Override
			public void actionPerformed(java.awt.event.ActionEvent evt) {
                jPasswordFieldActionPerformed(evt);
            }
        });

        jButtonLogin.setText("Login");
        jButtonLogin.addActionListener(new java.awt.event.ActionListener() {
            @Override
			public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonLoginActionPerformed(evt);
            }
        });

        jLabelSignUp.setFont(new java.awt.Font("Trebuchet MS", 0, 12)); // NOI18N
        jLabelSignUp.setForeground(new java.awt.Color(255, 255, 255));
        jLabelSignUp.setText("<html><u>New to Loan-a-Book?</u></html>");
        jLabelSignUp.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        jLabelSignUp.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
			public void mouseClicked(java.awt.event.MouseEvent evt) {
                jLabelSignUpMouseClicked(evt);
            }
        });

        jLabelConstructDB.setBackground(new java.awt.Color(255, 255, 255));
        jLabelConstructDB.setFont(new java.awt.Font("Trebuchet MS", 0, 12)); // NOI18N
        jLabelConstructDB.setForeground(new java.awt.Color(255, 255, 255));
        jLabelConstructDB.setText("<html><u>Construct The DB</u></html>");
        jLabelConstructDB.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        jLabelConstructDB.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
			public void mouseClicked(java.awt.event.MouseEvent evt) {
                jLabelConstructDBMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout jPanelFullWindowLayout = new javax.swing.GroupLayout(jPanelFullWindow);
        jPanelFullWindow.setLayout(jPanelFullWindowLayout);
        jPanelFullWindowLayout.setHorizontalGroup(
            jPanelFullWindowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelFullWindowLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanelFullWindowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanelFullWindowLayout.createSequentialGroup()
                        .addGroup(jPanelFullWindowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jTextFieldUserName, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(jPanelFullWindowLayout.createSequentialGroup()
                                .addGap(19, 19, 19)
                                .addComponent(jLabelUserName)))
                        .addGroup(jPanelFullWindowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanelFullWindowLayout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jPasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButtonLogin)
                                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addGroup(jPanelFullWindowLayout.createSequentialGroup()
                                .addGap(25, 25, 25)
                                .addComponent(jLabelPassword, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                    .addGroup(jPanelFullWindowLayout.createSequentialGroup()
                        .addComponent(jLabelWelcome)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addComponent(jLabelSignUp)
                    .addComponent(jLabelConstructDB)))
        );
        jPanelFullWindowLayout.setVerticalGroup(
            jPanelFullWindowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelFullWindowLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabelWelcome)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanelFullWindowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelUserName)
                    .addComponent(jLabelPassword))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanelFullWindowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextFieldUserName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jPasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonLogin))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabelSignUp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabelConstructDB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanelFullWindow, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanelFullWindow, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jTextFieldUserNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldUserNameActionPerformed
        executeLogin();
    }//GEN-LAST:event_jTextFieldUserNameActionPerformed

    private void jButtonLoginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonLoginActionPerformed
        executeLogin();
    }//GEN-LAST:event_jButtonLoginActionPerformed

    @SuppressWarnings("unchecked")
    private boolean executeLogin() throws HeadlessException {
        jButtonLogin.setVisible(false);
        BaseObject myUser = null;
        try {

            List<BaseObject> userList = (List<BaseObject>) DBAccessEngine.User().select(jTextFieldUserName.getText());

            if (userList.isEmpty()) {
                JOptionPane.showMessageDialog(this, "Invalid username!", "Error", JOptionPane.ERROR_MESSAGE);
                jButtonLogin.setVisible(true);
                return true;
            }

            String hashedPass = SHA1.toSHA1(getTextFromPasswordField(jPasswordField));
            if (!((User) userList.get(0)).getPassword().equals(hashedPass)) {
                JOptionPane.showMessageDialog(this, "Invalid password!", "Error", JOptionPane.ERROR_MESSAGE);
                jButtonLogin.setVisible(true);
                return true;
            }

            myUser = userList.get(0);

        } catch (DBAccessException ex) {
            ex.printStackTrace();
            jButtonLogin.setVisible(true);
        }
        MainForm.runGUI((User) myUser);
        dispose();
        return false;
    }

    private void jLabelSignUpMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabelSignUpMouseClicked
        SignUpForm.runGUI(this);
        setVisible(false);
    }//GEN-LAST:event_jLabelSignUpMouseClicked

    private void jPasswordFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jPasswordFieldActionPerformed
        executeLogin();
    }//GEN-LAST:event_jPasswordFieldActionPerformed

    private void jLabelConstructDBMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabelConstructDBMouseClicked
        Object[] options = {"Yes","No"};
        int n = JOptionPane.showOptionDialog(null,
                "Loan-a-Book is about to initialize your DB.\n"
                + "Would you like to proceed?",
                "Warning",
                JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE,
                null,
                options,
                options[1]);

        if (n == 1) {
            return;
        }
        JFrameConstructDB.runGUI(this);
        setVisible(false);
    }//GEN-LAST:event_jLabelConstructDBMouseClicked

    public static void runGUI() {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(AuthenticationForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AuthenticationForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AuthenticationForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AuthenticationForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new AuthenticationForm().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonLogin;
    private javax.swing.JLabel jLabelConstructDB;
    private javax.swing.JLabel jLabelPassword;
    private javax.swing.JLabel jLabelSignUp;
    private javax.swing.JLabel jLabelUserName;
    private javax.swing.JLabel jLabelWelcome;
    private javax.swing.JPanel jPanelFullWindow;
    private javax.swing.JPasswordField jPasswordField;
    private javax.swing.JTextField jTextFieldUserName;
    // End of variables declaration//GEN-END:variables
}
